package net.mycrub.bitwise.core.impl;

import java.io.InputStream;
import java.io.OutputStream;

import net.mycrub.bitwise.core.util.DeserializationException;
import net.mycrub.bitwise.core.util.Random;
import net.mycrub.bitwise.core.util.SerializationException;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class LinearLayerFactory {

    public static LinearLayer createRandom(int inputSize, int outputSize,
            double operatorMin, double operatorMax, double mutatorMin,
            double mutatorMax, double mutationChance, double combinationChance,
            double retroactionAmplitude) {
        double[][] o = new double[outputSize][inputSize];
        double[][] m = new double[outputSize][inputSize];

        for (int r = 0; r < outputSize; r++) {
            for (int c = 0; c < inputSize; c++) {
                o[r][c] = operatorMin + Random.next()
                        * (operatorMax - operatorMin);
                m[r][c] = mutatorMin + Random.next()
                        * (mutatorMax - mutatorMin);
            }
        }

        LinearLayer l = new LinearLayer(o, m);
        l.setMutationChance(mutationChance);
        l.setCombinationChance(combinationChance);
        l.setRetroactionAmplitude(retroactionAmplitude);

        return l;
    }

    public static LinearLayer read(InputStream serialized)
            throws DeserializationException {
        Serializer s = new Persister();
        try {
            return s.read(LinearLayer.class, serialized);
        } catch (Exception e) {
            throw new DeserializationException(LinearLayer.class, e);
        }
    }

    public static void write(LinearLayer l, OutputStream serialized)
            throws SerializationException {
        Serializer s = new Persister();
        try {
            s.write(l, serialized);
        } catch (Exception e) {
            throw new SerializationException(LinearLayer.class, e);
        }
    }

}
